package com.mflex.mwms.http.interceptor;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import androidx.appcompat.app.AlertDialog;

import com.mflex.mwms.MyApp;
import com.mflex.mwms.activity.LoginActivity;
import com.mflex.mwms.collector.ActivityCollector;
import com.mflex.mwms.utils.XToastUtils;
import com.xuexiang.xhttp2.interceptor.BaseExpiredInterceptor;
import com.xuexiang.xhttp2.model.ExpiredInfo;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JSONUtils;

import okhttp3.Response;

public class CustomExpiredInterceptor extends BaseExpiredInterceptor {
    /**
     * Token失效，需要重新获取token的code码
     */
    public static final int TOKEN_INVALID = 100;
    /**
     * 缺少Token
     */
    public static final int TOKEN_MISSING = TOKEN_INVALID + 1;
    /**
     * 认证失败
     */
    public static final int AUTH_ERROR = TOKEN_MISSING + 1;

    @Override
    protected ExpiredInfo isResponseExpired(Response oldResponse, String bodyString) {
        String state = JSONUtils.getString(bodyString, "state", "");
        String message = JSONUtils.getString(bodyString, "message", "");
        ExpiredInfo expiredInfo;
        if (StringUtils.equals("token", state) && StringUtils.equals("Token验证失败。", message)) {
            expiredInfo = new ExpiredInfo(999);
            expiredInfo.setExpiredType(999)
                    .setBodyString(message);
        } else {
            expiredInfo = new ExpiredInfo(0);
        }
        return expiredInfo;
    }

    @Override
    protected Response responseExpired(Response oldResponse, Chain chain, ExpiredInfo expiredInfo) {
        switch (expiredInfo.getExpiredType()) {
            case 999:
                Intent intent=new Intent("com.mflex.mwms.activity.FORCE_OFFLINE");
                MyApp.getAppContext().sendBroadcast(intent);
                break;
            default:
                break;
        }
        return null;
    }

    /**
     * 失效类型
     */
    static final class ExpiredType {

        /**
         * token失效
         */
        static final int KEY_TOKEN_EXPIRED = 10;

        /**
         * 未注册的用户
         */
        static final int KEY_UNREGISTERED_USER = KEY_TOKEN_EXPIRED + 1;
    }
}
